package com.sandy.demo.auth

import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails

import java.util.concurrent.ConcurrentHashMap

@Slf4j
@CompileStatic
class MemoryTokenStorageService implements TokenStorageService {

    private static ConcurrentHashMap<String, UserDetails> map = new ConcurrentHashMap<>();

    @Override
    UserDetails loadUserByToken(String tokenValue) throws TokenNotFoundException {
        log.debug "Searching in Memory for UserDetails of token ${tokenValue}"

        def userDetails = map.get(tokenValue)

        if (userDetails) {
            return new User(userDetails.username, "N/A", userDetails.authorities)
        } else {
            throw new TokenNotFoundException("Token ${tokenValue} not found")
        }
    }

    @Override
    void storeToken(String tokenValue, UserDetails principal) {
        log.debug "Principal: ${principal}"
        map.put(tokenValue, principal);
    }

    @Override
    void removeToken(String tokenValue) throws TokenNotFoundException {
        log.debug "Removing token: ${tokenValue}"
        map.remove(tokenValue)
    }

}
